<?php

namespace End01here\Weather;

use End01here\Weather\Exceptions\HttpException;
use End01here\Weather\Exceptions\InvalidArgumentException;
use GuzzleHttp\Client;

class Weather
{

    protected $key;

    protected $guzzleOptions = [];

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    function getHttpClient()
    {
        return new Client($this->guzzleOptions);
    }

    function setGuzzleOptions(array $options)
    {
        $this->guzzleOptions = $options;
    }


    function getWeather($city, string $type = 'base', string $format = 'json')
    {

        $url = 'https://restapi.amap.com/v3/weather/weatherInfo';

        if(!in_array(strtolower($format),['xml','json'])){
            throw new InvalidArgumentException('Invalid type format(xml/json): '.$format);
        }
        if(!in_array(strtolower($type),['base','all'])){
            throw new InvalidArgumentException('Invalid type value(base/all): '.$type);
        }


        $query = array_filter([
            'key' => $this->key,
            'city' => $city,
            'output' => $format,
            'extensions' => $type,
        ]);

        try{
            $response = $this->getHttpClient()->get($url, [
                'query' => $query,
            ])->getBody()->getContents();

            return 'json' === $format ? json_decode($response, true) : $response;
        }catch (\Exception $e){
            throw new HttpException($e->getMessage(), $e->getCode(), $e);
        }

    }



}